import axios from "axios";
import Vue from 'vue';
import router from '../router'
import { Message } from 'element-ui'


// 配置请求的根路径
axios.defaults.baseURL = 'http://localhost:8080/api';
//axios请求拦截
axios.interceptors.request.use(req => {
    //携带token
    if (window.sessionStorage.getItem('token') !== "null")
        req.headers.token = window.sessionStorage.getItem('token');
    return req;
})

//axios请求拦截
axios.interceptors.response.use(res => {
    //
    const { code, msg } = res.data;
    if (code === 200) {
        return res;
    } else if (code === 401) {
        Message.error(msg)
        setTimeout(() => {
            router.push('/login');
        }, 1500)
        window.sessionStorage.removeItem("token");
        return Promise.reject(msg);
    } else if (code === 403) {
        Message.error(msg)
        setTimeout(() => {
            router.push('/login');
        }, 1500)
        return Promise.reject(msg);
    } else {
        return res;
    }
})


Vue.prototype.$http = axios